iT邦幫忙

2024 iThome 鐵人賽

DAY 11
1
Software Development

Rust 學得動嗎系列 第 11

[Day 11] Rust 的模組系統、套件管理與測試

  • 分享至 

  • xImage
  •  

今天,我們來介紹 Rust 的模組系統、套件管理和測試。這些主題對於大型專案、管理依賴關係和確保程式碼品質有很大的幫助。

1. 模組系統(Module System)

Rust 的模組系統允許我們組織和重用程式碼。

建立模組

// 在 src/lib.rs 或 src/main.rs 中
mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

pub fn eat_at_restaurant() {
    front_of_house::hosting::add_to_waitlist();
}

使用 use 關鍵字

use crate::front_of_house::hosting;

pub fn eat_at_restaurant() {
    hosting::add_to_waitlist();
}

也可以拆分模組到不同檔案

// src/front_of_house.rs
pub mod hosting {
    pub fn add_to_waitlist() {}
}

// src/lib.rs
mod front_of_house;

pub fn eat_at_restaurant() {
    front_of_house::hosting::add_to_waitlist();
}

2. 套件管理(Package Management)

Rust 使用 Cargo 作為其套件管理器和建構系統。

建立新專案

cargo new my_project
cd my_project

管理依賴

Cargo.toml 文件中增加依賴:

[dependencies]
serde = "1.0"
reqwest = { version = "0.11", features = ["json"] }

建構和執行

cargo build
cargo run

3. 測試(Testing)

Rust 有一個內建的測試框架,使得編寫和執行測試變得簡單。

單元測試

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }

    #[test]
    #[should_panic(expected = "除以零")]
    fn it_panics() {
        divide(10, 0);
    }
}

fn divide(a: i32, b: i32) -> i32 {
    if b == 0 {
        panic!("除以零");
    }
    a / b
}

整合測試

tests 目錄下建立檔案:

// tests/integration_test.rs
use my_project;

#[test]
fn test_add() {
    assert_eq!(my_project::add(2, 2), 4);
}

執行測試

cargo test

實際應用範例:簡單的計算器套件

讓我們建立一個簡單的計算器套件,展示模組化、文件化和測試。

// src/lib.rs
//! 一個簡單的計算器套件。
//! 
//! 這個套件提供基本的數學運算功能。

/// 加法模組
pub mod add {
    /// 執行兩個數字的加法。
    ///
    /// # 範例
    ///
    /// ```
    /// use my_calculator::add::add;
    /// assert_eq!(add(2, 2), 4);
    /// ```
    pub fn add(a: i32, b: i32) -> i32 {
        a + b
    }
}

/// 減法模組
pub mod subtract {
    /// 執行兩個數字的減法。
    ///
    /// # 範例
    ///
    /// ```
    /// use my_calculator::subtract::subtract;
    /// assert_eq!(subtract(5, 3), 2);
    /// ```
    pub fn subtract(a: i32, b: i32) -> i32 {
        a - b
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_add() {
        assert_eq!(add::add(2, 2), 4);
    }

    #[test]
    fn test_subtract() {
        assert_eq!(subtract::subtract(5, 3), 2);
    }
}
# Cargo.toml
[package]
name = "my_calculator"
version = "0.1.0"
edition = "2024"

[dependencies]

https://ithelp.ithome.com.tw/upload/images/20240925/20140358LuIsTT7R95.png

補充資料

  • 如何使用 Cargo 的工作區來管理多個相關的套件。
  • 研究如何使用 條件編譯 來為不同的目標平台或功能編譯不同的程式碼。

上一篇
[Day 10] Rust 的進階特性:不安全程式碼、進階特徵與型別系統
下一篇
[Day 12] Rust 的進階模式匹配與Macro System
系列文
Rust 學得動嗎13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言